package android.autocode.selector;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import android.autocode.Cmd;

public class Selector implements Cmd {
	private static final String CMD = "selector";
	private static final String HINT = CMD + " /path/drawable";

	@Override
	public String getCmd() {
		return CMD;
	}

	@Override
	public String getHint() {
		return HINT;
	}

	@Override
	public void genCode(String[] args) {
		if (args == null || args.length < 1) {
			System.out.println(HINT);
			return;
		}

		String path = args[0];

		File folder = new File(path);
		String[] list = folder.list();

		ArrayList<SelectorData> selectorList = new ArrayList<SelectorData>();
		for (String file : list) {
			String finalName = getFinalName(file);
			if (finalName.length() <= 0) {
				continue;
			}

			int stateIndex = getStateIndex(file);
			if (stateIndex >= SelectorData.STATE_ARRAY.length) {
				continue;
			}

			SelectorData selectorData = null;
			for (SelectorData child : selectorList) {
				if (child.finalName.equals(finalName)) {
					selectorData = child;
				}
			}

			if (selectorData == null) {
				selectorData = new SelectorData();
				selectorData.finalName = finalName;
				selectorList.add(selectorData);
			}

			selectorData.stateArray[stateIndex] = getPureName(file);
		}

		for (SelectorData child : selectorList) {
			printCode(child, path);
		}
	}

	private void printCode(SelectorData selector, String path) {
		FileWriter fw = null;
		try {
			fw = new FileWriter(path + "/" + selector.finalName + ".xml");
			fw.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			fw.write("<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n");

			for (int i = 0; i < SelectorData.STATE_ARRAY.length; i++) {
				String state = selector.stateArray[i];
				if (state != null) {
					if (SelectorData.STATE_ARRAY[i]
							.equals(SelectorData.STATE_NORMAL)) {
						fw.write("    <item android:drawable=\"@drawable/" + state
								+ "\" />\n");
					} else {
						fw.write("    <item android:state"
								+ SelectorData.STATE_ARRAY[i] + "=\"true\"\n");
						fw.write("        android:drawable=\"@drawable/" + state
								+ "\"/>\n");
					}
				}
			}

			fw.write("</selector>\n");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private String getPureName(String name) {
		int dotIndex = name.lastIndexOf(".");
		return name.substring(0, dotIndex);
	}

	private String getFinalName(String name) {
		String finalName = getPureName(name);
		for (String state : SelectorData.STATE_ARRAY) {
			finalName = finalName.replaceAll(state, "");
		}
		return finalName;
	}

	private int getStateIndex(String name) {
		int stateIndex = 0;
		for (String state : SelectorData.STATE_ARRAY) {
			if (name.contains(state)) {
				break;
			}
			stateIndex++;
		}
		return stateIndex;
	}

}
